package com.dingpeikeji.quickdeer.mobile.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dingpeikeji.quickdeer.core.modules.distribution.dao.TDistributionDao;
import com.dingpeikeji.quickdeer.core.modules.distribution.entity.DistributionInfo;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.mobile.dao.OrderDao;
import com.dingpeikeji.quickdeer.mobile.entity.OrderInfo;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;

@Service
@Transactional(readOnly = true)
public class OrderService {
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private TDistributionDao tDistributionDao;

	/**
	 * 获取计佣订单List
	 */
	public List<OrderInfo> getOrderList(String userId) {
		return orderDao.getOrderList(userId);
	}

	/**
	 * 获取未结算计佣订单List
	 */
	public List<OrderInfo> getNoBalanceList(String userId) {
		return orderDao.getNoBalanceList(userId);
	}

	// 将订单号存入tem_orders表 存储过程使其规定时间取消订单
	public Integer insertTmpOrders(String orderId) {
		return orderDao.insertTmpOrders(orderId);
	}

	@Transactional
	public Integer updateOrderBalance(DistributionInfo distributionInfo, String type) throws Exception {
		int z = 0;
		if (distributionInfo != null) {
			// 订单详情部分
			List<OrderInfo> info = getOrderList(distributionInfo.getUserId());
			long time = ValidateTool.getMonthFirstDay(df.format(distributionInfo.getCreateTime()));// 获取指定月的第一天
			for (int i = 0; i < info.size(); i++) {
				if (info.get(i).getCreateDate().getTime() < time && info.get(i).getIsBalance().equals("2")) {// 如果计佣订单的完单时间小于于提现日期月第一天则计算该记录
					z = orderDao.updateOrderBalance(info.get(i).getOrderId(), type);
					DistributionInfo a = new DistributionInfo();
					a.setWithdrawSettleId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
					a.setOrderId(info.get(i).getOrderId());
					a.setDistributionId(distributionInfo.getDistributionId());
					a.setPrice(info.get(i).getDueAmount());
					a.setOrderName(info.get(i).getOrderName());
					a.setCreateDate(info.get(i).getCreateDate());
					a.setSettleCreateTime(new Date());
					tDistributionDao.insertWithdrawSettle(a);
				}
			}
		}
		return z;
	}

	/**
	 * 设置订单使用了优惠券
	 * 
	 * @param orderId
	 * @return
	 */
	public Integer updateOrderUseCupon(String orderId) {
		return orderDao.updateOrderUseCupon(orderId);
	}
	
	//线下订单改状态
	public void updateOffline(TOrders orders){
		orderDao.updateOffline(orders);
	}

}
